import { useMount } from "@/hooks";
import { TreasuryGoods } from "@/types";
import { Card, CdnImage, Form, PrimaryButton, TextArea, TextInput } from "@/ui-components";
import { View } from "@tarojs/components";
import { useState } from "react";
import { useAppSelector } from "@/store/hooks";
import Taro from "@tarojs/taro";
import to from "await-to-js";
import { dialog } from "@/utils";
import { UserTreasury } from "@/store/treasurySlice";
import { exchageTreasuryGoods, getTreasuryGoodsDetail } from "../../network";
import './index.scss'

const onExchange = async (treasuryGoods: TreasuryGoods, userTreasury ?: UserTreasury) => {
  if (!userTreasury) {
    Dialog.toast('用户信息错误')
    return
  }
  if (userTreasury.userScore < treasuryGoods.score) {
    Dialog.toast('积分不足')
    return
  }
  Dialogconfirm({
    content: `确认消耗${treasuryGoods.score}积分兑换${treasuryGoods.name}吗？`,
    onConfirm: async () => {
      const [err] = await to(exchageTreasuryGoods({
        treasuryGoodsId: treasuryGoods.treasuryGoodsId,
        treasuryId: treasuryGoods.treasuryId
      }))
      if (err) {
        Dialog.toast(err.message || '兑换失败')
        return
      }
      Dialog.toast('兑换成功')
      Taro.navigateBack()
    }
  })
}


export default function TreasuryGoodsExchangePage() {

  const [treasuryGoods, setTreasuryGoods] = useState<TreasuryGoods | undefined>(undefined)
  const userTreasury = useAppSelector(state => state.treasury.userTreasury)

  useMount(async () => {
    const treasuryGoodsId = Number(Taro.getCurrentInstance().router?.params.treasuryGoodsId)
    if (Number.isNaN(treasuryGoodsId)) {
      Dialog.toast('参数错误')
      return
    }
    const [err, goods] = await to(getTreasuryGoodsDetail(treasuryGoodsId))
    if (err) {
      Dialog.toast(err.message || '获取商品信息失败')
      return
    }
    setTreasuryGoods(goods)
  })

  if (treasuryGoods) {
    return (
      <View className='treasuty-goods-exchange'>
        <Card className='treasury-goods-exchange-content'>
          <CdnImage src={treasuryGoods.image} className='treasury-goods-image p-normal border-radius-small' />
          <View className='text-title ph-normal'>{treasuryGoods.name}</View>
          <Form className='mt-small'>
            <TextInput disabled value={String(userTreasury?.userScore)} label='我的积分' placeholder='0' />
            <TextInput disabled value={String(treasuryGoods.score)} label='消耗积分' placeholder='0' />
            { treasuryGoods.exchangeNote && <TextArea label='兑换备注' placeholder='请输入兑换备注' disabled value={treasuryGoods.exchangeNote} /> }
          </Form>
        </Card>
        <PrimaryButton text='确认兑换' onClick={() => onExchange(treasuryGoods, userTreasury)} />
      </View>
    )
  }
}